package cn.edu.zut.sunday.sst.controller;

import cn.edu.zut.sunday.base.controller.GenericController;
import cn.edu.zut.sunday.sst.domain.SstInfo;
import cn.edu.zut.sunday.sst.service.SstInfoService;
import cn.edu.zut.sunday.sst.vo.SstInfoQuery;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import io.swagger.annotations.Api;
import java.util.ArrayList;
import java.util.Map;
import javax.persistence.criteria.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api("sst-数据集表接口")
@RestController
@CrossOrigin
@RequestMapping("/sst/sstInfo")
public class SstInfoController extends GenericController<SstInfo, Integer, SstInfoService> {

    /**
     * 创建sstInfoService对象
     * @param sstInfoService 由IOC自动注入服务对象
     */

    @Autowired
    public void setSstInfoService(SstInfoService sstInfoService) {
        this.service = sstInfoService;
    }

    @Override
    protected Specification<SstInfo> createSpecification(String requestBodyStr) {
        try {
            // 处理label为空字符串的情况
            final Gson gson = new Gson();
            final Map<Object, Object> map = gson.fromJson(requestBodyStr, Map.class);
            final Object              label = map.getOrDefault("label", "");
            if ("".equals(label)) {
                map.remove("label");
            }

            requestBodyStr = gson.toJson(map);
            // 解析request body
            final SstInfoQuery infoQuery = gson.fromJson(requestBodyStr,
              SstInfoQuery.class);
            final ArrayList<Predicate> list = Lists.newArrayList();

            return (root, query, cb) -> {
                if (StringUtils.isNotEmpty(infoQuery.getSentence())) {
                    list.add(cb.like(root.get("sentence"), sqlLike(infoQuery.getSentence())));
                }
                if (StringUtils.isNotEmpty(infoQuery.getTokens())) {
                    list.add(cb.like(root.get("tokens"), sqlLike(infoQuery.getTokens())));
                }
                if (infoQuery.getLabel() > 0.0) {
                    list.add(cb.equal(root.get("label"), infoQuery.getLabel()));
                }
                return cb.and(list.toArray(new Predicate[0]));
            };
        } catch (JsonSyntaxException e) {
            log.error("反序列化对象失败: {}", requestBodyStr);
        }
        return null;
    }
}
